<template>
    <el-card>
        <div class="title-bar">
            <div>
                <div></div>
                <span>{{ title }}</span>
            </div>
        </div>
        <div class="message-bar">
            <span>居民信息</span>
            <el-form ref="ruleResidentRef" :rules="residentRules" label-width="80px" :inline="true"
                :model="residentFormData" class="demo-form-inline" style="--el-font-size-base:13px;">
                <el-form-item label="姓名" prop="name" v-if="formData._id">
                    <el-input :disabled="true" :value="formData.residentId?.name">
                    </el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="name" v-else>
                    <el-select clearable v-model="residentFormData._id">
                        <el-option value="" label=" 请选择" />
                        <el-option v-for="item in residents" :label="item.name" :key="item._id"
                            :value="item._id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="身份证号" prop="IDnumber">
                    <el-input v-model="residentFormData.IDnumber">
                    </el-input>
                </el-form-item>
                <el-form-item label="性别" prop="gender">
                    <el-select clearable v-model="residentFormData.gender">
                        <el-option value="1" label="男" />
                        <el-option value="0" label="女" />
                    </el-select>
                </el-form-item>
                <el-form-item label="出生年月" prop="birthday">
                    <el-date-picker v-model="residentFormData.birthday" type="date" placeholder="请选择日期"
                        style="width: 200px;height: 40px;" />
                </el-form-item>
                <el-form-item label="联系电话" prop="phone">
                    <el-input placeholder="请输入" v-model="residentFormData.phone">
                    </el-input>
                </el-form-item>
                <el-form-item label="现居地">
                    <el-input placeholder="请输入" style="width: 300px;" v-model="residentFormData.address">
                    </el-input>
                </el-form-item>
                <el-form-item label="居民标签">
                    <el-select clearable v-model="residentFormData.tags">
                        <el-option value="" label="请选择" />
                        <el-option v-for="item in tagData" :label="item.name" :key="item._id"
                            :value="item._id"></el-option>
                    </el-select>
                </el-form-item>
                <div style="width: 100%;height: auto;display: flex;">
                    <div
                        style="height: 40px;width: 80px;font-size: 13px;color: #999;margin-right: 10px;padding-right: 12px;text-align: right;line-height: 40px;box-sizing: border-box;">
                        家庭成员</div>
                    <div class="relation-bar"
                        style="display: grid;grid-template-columns: repeat(5,200px);justify-content: space-between;width: auto;row-gap: 20px;column-gap: 25px;">
                        <div class="relation-box" v-for="item in relationData">
                            <img :src="item.otherId.avatar" alt="">
                            <section class="relation-message" style="height: auto;width:126px;">
                                <div style="height: 18px;display: flex;width: 133px;">
                                    <p style="line-height: 16px;" class="nameBar">{{
                                        item.otherId.name }}</p>
                                    <span style="margin: 0 20px 0 0;line-height: 12px;"> 26岁 </span>
                                    <img style="width: 12px;height: 12px;" src="/src/assets/girls.png" alt=""
                                        v-if="!item.otherId.gender">
                                    <img src="/src/assets/boys.png" alt="" v-else>
                                </div>
                                <span>{{ '关系：' + item.relationship }}</span>
                            </section>
                        </div>
                        <div class="addPart" style="color: #2984F8;cursor: pointer;height: 84px;" @click="addRelation">
                            +关联家庭成员</div>
                    </div>
                    <div></div>
                </div>
            </el-form>
            <div class="button-bar">
                <el-button type="primary" @click="toUpdateResident(ruleResidentRef)">保存</el-button>
            </div>

        </div>
        <div class="message-bar">
            <span>服务信息</span>
            <el-form ref="ruleServiceRef" :rules="serviceDataRules" label-width="80px" :inline="true" :model="formData"
                class="demo-form-inline" style="--el-font-size-base:13px;">
                <el-form-item label="服务编号">
                    <div>{{ formData._id }}</div>
                </el-form-item>

                <el-form-item label="服务机构" prop="organizationId">
                    <el-select clearable v-model="formData.organizationId">
                        <el-option :value="item._id" :label="item.name" v-for="item in organizationData"
                            :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="服务团队" prop="teamId">
                    <el-select clearable v-model="formData.teamId" :disabled="!formData.organizationId">
                        <el-option :value="item._id" :label="item.name" v-for="item in teamData" :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="服务医生" prop="doctorId">
                    <el-select clearable v-model="formData.doctorId" :disabled="!formData.teamId">
                        <el-option :value="item._id" :label="item.name" v-for="item in doctorData" :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="服务包" prop="serviceDataPackId">

                    <el-select clearable v-model="formData.servicePackId" :disabled="!formData.organizationId">
                        <el-option :value="item._id" :label="item.name" v-for="item in packData" :key="item._id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="服务项目" prop="serviceItemId">
                    <el-select clearable v-model="formData.serviceItemId" :disabled="!formData.servicePackId">
                        <el-option :value="item._id" :label="item.name + ' ' + '剩余' + item.count + '次'"
                            v-for="item in serviceItemData" :key="item._id">
                            {{ item.name }}
                            <span style="color: red;">{{ '剩余' + item.count + '次' }}</span>
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="服务地点" prop="place" :disabled="!formData.serviceItemId">
                    <el-select clearable v-model="formData.place">
                        <el-option value="" label="请选择" />
                        <el-option value="上门服务" label="上门服务" />
                        <el-option value="机构门诊" label="机构门诊" />


                    </el-select>
                </el-form-item>

                <el-form-item label="服务时间">
                    <el-date-picker style="width: 200px;height: 40px;" v-model="formData.time" type="datetime"
                        placeholder="请选择服务时间" />
                </el-form-item>
                <el-form-item label="签约备注" style="height: 120px;display: flex;">
                    <el-input v-model="formData.remark" style="width: 582px;height: 110px;" :rows="5" type="textarea"
                        placeholder="请输入签约备注" />
                </el-form-item>
            </el-form>
        </div>

        <div class="button-bar">
            <el-button type="primary" @click="toUpdate(ruleServiceRef)">保存</el-button>
            <el-button @click="$router.back">返回</el-button>
        </div>
    </el-card>

    <AddRelation ref="relationRef"></AddRelation>
</template>

<script setup>
import { onMounted, ref, useTemplateRef, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { findOrganizationsApi } from '../../../api/organization';
import { searchTeamsApi } from '../../../api/teamManage';
import { searchDoctorsApi } from '../../../api/doctors';
import { findPackApi, getPackApi } from '../../../api/servicePack';
import { ElMessage } from 'element-plus';
import { findTagsApi } from '../../../api/tags';
import AddRelation from '../../resident/AddRelation.vue';
import { findResidentInfoApi, findResidentRelationApi, getREsidentDetailApi, upDateREsidentApi } from '../../../api/resident';
import { addServiceApi, getServiceDetailApi, updateServiceApi } from '../../../api/serviceManage';
import { searchItemByPackApi } from '../../../api/serviceItem';
import { getPackByOrganizationApi } from '../../../api/servicePacksge';
const router = useRouter()
const route = useRoute()
// 签约周期
const periodSign = ref('')
// 费用
const signPrice = ref('')

const formData = ref({


})

const title = ref('添加服务信息')

watch(() => formData.value.servicePackId, () => {
    getPack()
})





//获取当前签约时间
function formatDate(date) {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
}

const residentFormData = ref({
    _id: '',
    name: '',
    IDnumber: '',
    gender: '',
    birthday: '',
    phone: '',
    address: '',
    tags: []
})

// 居民
const residents = ref([])

// 获取居民
function findResidents() {
    findResidentInfoApi()
        .then(res => {
            if (res.code == 200) {
                residents.value = res.data.rows
            }
        })
}

// 机构
const organizationData = ref([])
function findOrganization() {
    findOrganizationsApi()
        .then(res => {
            if (res.code == 200) {
                organizationData.value = res.data.rows
            }
        })
}

// 标签数据
const tagData = ref([])

function findTag() {
    findTagsApi()
        .then(res => {
            if (res.code == 200) {
                tagData.value = res.data.rows
            }
        })
}



// 获取居民详情
function getResident() {
    getREsidentDetailApi({ _id: residentFormData.value._id })
        .then(res => {
            if (res.code == 200) {
                residentFormData.value = res.data
            }
        })
}

// 团队
const teamData = ref([]);
function findTeam() {
    searchTeamsApi({ organizationId: formData.value.organization })
        .then(res => {
            if (res.code == 200) {
                teamData.value = res.data.rows
            }
        })
}

watch(() => formData.value.organizationId, () => {

    formData.value.teamId = ''
    formData.value.servicePackId = ''

    findTeam()
    getPack()
})

// 医生
const doctorData = ref([]);
function findDoctor() {
    searchDoctorsApi({ teamId: formData.value.teamId })
        .then(res => {
            if (res.code == 200) {
                doctorData.value = res.data.rows
            }
        })
}

watch(() => formData.value.teamId, () => {

    formData.value.doctorId = ''

    findDoctor()
})
// 添加服务
function addServiceData() {
    addServiceApi({
        ...formData.value,

        residentId: residentFormData.value._id
    })
        .then(res => {
            router.back()
            if (res.code == 200) {
                ElMessage({
                    message: '服务信息添加成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(res.message)
            }
        })
}

const relationRef = useTemplateRef('relationRef')
// 添加关系
function addRelation() {
    relationRef.value?.addRelationship(residentFormData.value._id)
    getRelation()
}


const serviceItemData = ref([])
// 获取服务项目
function getServiceItem() {
    searchItemByPackApi({ servicePackId: formData.value.servicePackId })
        .then(res => {
            if (res.code == 200) {
                serviceItemData.value = res.data
            }
        })
}
watch(() => formData.value.servicePackId, () => {

    formData.value.serviceItemId = ''

    getServiceItem()
})

// 修改服务
function update() {
    updateServiceApi(formData.value)
        .then(res => {
            if (res.code == 200) {
                router.back()
                ElMessage({
                    message: '服务信息保存成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(res.message)
            }
        })
}
// 修改居民
function updateResident() {
    upDateREsidentApi(residentFormData.value)
        .then(res => {
            if (res.code == 200) {

                ElMessage({
                    message: '居民信息保存成功',
                    type: 'success',
                })
            } else {
                ElMessage.error(res.message)
            }
        })
}

// 服务包
const packData = ref([])
function getPack() {
    getPackByOrganizationApi({ organizationId: formData.value.organizationId })
        .then(res => {
            if (res.code == 200) {
                packData.value = res.data[0]
                console.log(111222, packData.value);

            }
        })
}



const serviceData = ref({})

// 获取服务详情
function getServiceDataDetail() {
    getServiceDetailApi({ _id: route.params._id })
        .then(res => {
            if (res.code == 200) {
                formData.value = res.data
                serviceId.value = res.data._id
                residentFormData.value = {
                    ...res.data.residentId

                }
            } else {
                formData.value.applyTime = formatDate(new Date())
            }
        })
}

const relationData = ref([])

// 获取亲属关系
function getRelation() {
    findResidentRelationApi
        ({ ownId: residentFormData.value._id })
        .then(res => {
            if (res.code == 200) {
                relationData.value = res.data
            }
        })
}

// // 获取服务包详情
// function getPack() {
//     getPackApi({ _id: formData.value.servicePack })
//         .then(res => {
//             if (res.code == 200) {
//                 periodSign.value = res.data.period;
//                 signPrice.value = res.data.price
//             }
//         })
// }

onMounted(() => {
    residentFormData.value._id = route.params._id
    findOrganization()
    findTeam()
    findDoctor()
    getPack()
    findTag()
    getServiceDataDetail()
    findResidents()
    getRelation()
    getServiceItem()
    residentFormData.value._d = route.params._id
    if (route.params._id) {
        title.value = '编辑服务信息'
    } else {
        title.value = '添加服务信息'
    }
})

watch(() => residentFormData.value._id, () => {
    getResident()
})

// 表单验证
const residentRules = ref({
    phone: [
        { required: true, message: '手机号不能为空', trigger: 'blur' },

    ],
    password: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'blur',
        },
    ],
    name: [
        {
            required: true,
            message: '姓名不能为空',
            trigger: 'blur',
        },
    ],
    birthday: [
        {
            required: true,
            message: '生日不能为空',
            trigger: 'blur',
        },
    ],
    IDnumber: [
        {
            required: true,
            message: '身份证号不能为空',
            trigger: 'blur',
        },
    ],
    gender: [
        {
            required: true,
            message: '性别不能为空',
            trigger: 'blur',
        },
    ],

})

const serviceDataRules = ref({
    organization: [
        {
            required: true,
            message: '机构不能为空',
            trigger: 'blur',
        },
    ],
    team: [
        {
            required: true,
            message: '团队不能为空',
            trigger: 'blur',
        },
    ],
    doctor: [
        {
            required: true,
            message: '签约医生不能为空',
            trigger: 'blur',
        },
    ],

    servicePack: [
        {
            required: true,
            message: '服务包不能为空',
            trigger: 'blur',
        },
    ],
    serviceItemId: [
        {
            required: true,
            message: '服务项目不能为空',
            trigger: 'blur',
        },
    ],
    place: [
        {
            required: true,
            message: '服务地点不能为空',
            trigger: 'change',
        },
    ],
})

// 修改服务
const toUpdate = (formEl) => {
    console.log(2);

    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            console.log(1);

            if (!formData.value._id) {
                addServiceData()
            } else {
                update()
            }
        } else {
            console.log('error submit!', fields)
        }
    })
}

// 修改居民
const toUpdateResident = (formEl) => {
    if (!formEl) return
    formEl.validate((valid, fields) => {
        if (valid) {
            updateResident()


            console.log('submit!')
        } else {
            console.log('error submit!', fields)
        }
    })
}


const ruleServiceRef = ref()
const ruleResidentRef = ref()

</script>

<style scoped>
.title-bar {
    height: 40px;
    border-bottom: 1px solid #dbdbdb;

}

.title-bar>view {
    height: 20px;
    display: flex;
    align-items: center;
}

.title-bar>view>view {
    height: 20px;
    background-color: var(--el-color-primary);
    width: 6px;
    border-radius: 16px;
    margin-right: 15px;
}

.title-bar span {
    color: var(--el-title-font-color);
    font-size: var(--el-title-font-size);
    font-weight: var(--el-title-font-weight);
}

.message-bar span {
    display: inline-block;
    font-size: 16px;
    color: #333;
    margin-bottom: 20px;
}

.message-bar {
    border-bottom: 1px solid #dbdbdb;
    margin-top: 20px;
}

.el-form-item div {
    height: 40px;
    width: 200px;
    line-height: 40px;
    font-size: 13px;
    color: #333;
}

.el-input,
.el-select {
    width: 200px;
    height: 40px;
}

.message-bar .el-form-item {
    margin-right: 100px;
    margin-bottom: 15px;
}

.button-bar {
    height: 40px;
    display: flex;
    justify-content: flex-start;
    margin-top: 20px;
    margin-bottom: 20px;
}

.relation-bar {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(5, 200px);
    justify-content: space-between;
    padding-right: 20px;
    min-height: 84px;
}

.relation-box {
    width: 200px;
    min-height: 84px;
    border-radius: 8px;
    border: 1px solid rgba(242, 242, 242, 1);
    display: flex;
    padding-top: 25px;
    padding-left: 20px;
    margin-bottom: 20px;
    box-sizing: border-box;
}

.relation-box>img {
    width: 40px;
    height: 40px;
    margin-right: 10px;
    border-radius: 50%;
}

.relation-bar .relation-box .relation-message {
    display: flex;
    flex-direction: column;
    justify-content: flex-start;
}

.relation-message>div {
    display: inline-block;
    display: flex;
    align-items: center;
    margin-bottom: 20px;
}

.relation-message>div>p {
    font-size: 16px;
    color: #333;
    margin: 0;
    margin-right: 6px;
    line-height: 16px;
}

.relation-message>div>span,
.relation-message span {
    font-size: 12px;
    color: #999;
    margin-right: 20px;
    line-height: 12px;
}

.relation-message>div>img {
    width: 15px;
    height: 15px;
}

.addPart {
    width: 200px;
    height: 40px;
    line-height: 40px;
    font-size: 13px;
    font-weight: 400;
    display: flex;
    align-items: center;
}

.nameBar {
    white-space: nowrap;
    /* 防止文本换行 */
    overflow: hidden;
    /* 隐藏超出部分 */
    text-overflow: ellipsis;
    /* 超出部分显示为省略号 */
    width: 50px;
}
</style>